// 个人中心页面逻辑
const InitData = require('../../utils/initData.js');

Page({
  data: {
    userInfo: {},
    stats: {
      totalQuestions: 0,
      completedQuestions: 0,
      correctRate: '0%',
      studyDays: 0
    },
    version: '1.0.0'
  },

  onLoad: function (options) {
    this.loadUserInfo();
    this.loadUserStats();
    
    // 移除自动初始化示例数据，让默认状态显示0
    // InitData.initAllSampleData();
  },

  onShow: function () {
    // 页面显示时刷新数据
    this.loadUserInfo();
    this.loadUserStats();
  },

  // 加载用户信息
  loadUserInfo: function () {
    const app = getApp();
    const userInfo = app.globalData.userInfo || wx.getStorageSync('userInfo') || {};
    this.setData({
      userInfo: userInfo
    });
  },

  // 更新登录状态（供全局调用）
  updateLoginStatus: function (isLoggedIn) {
    if (isLoggedIn) {
      this.loadUserInfo();
    } else {
      this.setData({
        userInfo: {}
      });
    }
  },

  // 加载用户统计数据
  loadUserStats: function () {
    // 获取真实的学习数据
    const studyHistory = wx.getStorageSync('studyHistory') || [];
    const wrongQuestions = wx.getStorageSync('wrongQuestions') || [];
    const favorites = wx.getStorageSync('favorites') || [];
    
    // 计算总题数（从题库中获取）
    const { questionCategories } = require('../../utils/questions.js');
    let totalQuestions = 0;
    questionCategories.forEach(category => {
      category.topics.forEach(topic => {
        totalQuestions += topic.questions.length;
      });
    });
    
    // 计算已做题目数和正确率
    let completedQuestions = 0;
    let correctCount = 0;
    studyHistory.forEach(record => {
      completedQuestions += record.questionCount || 0;
      correctCount += record.correctCount || 0;
    });
    const correctRate = completedQuestions > 0 ? Math.round((correctCount / completedQuestions) * 100) + '%' : '0%';
    
    // 计算学习天数
    const studyDays = this.calculateStudyDays(studyHistory);
    
    const stats = {
      totalQuestions: totalQuestions,
      completedQuestions: completedQuestions,
      correctRate: correctRate,
      studyDays: studyDays
    };
    
    this.setData({ stats: stats });
    
    // 保存统计数据
    wx.setStorageSync('userStats', stats);
  },

  // 计算学习天数
  calculateStudyDays: function (studyHistory) {
    if (studyHistory.length === 0) return 0;
    
    const dates = new Set();
    studyHistory.forEach(record => {
      if (record.date) {
        dates.add(record.date);
      }
    });
    
    return dates.size;
  },

  // 处理登录
  handleLogin: function () {
    const app = getApp();
    app.manualLogin().then((userInfo) => {
      this.loadUserInfo();
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });
    }).catch((err) => {
      wx.showToast({
        title: '登录失败',
        icon: 'error'
      });
    });
  },

  // 处理退出登录
  handleLogout: function () {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          const app = getApp();
          app.logout();
          this.loadUserInfo();
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  },

  // 初始化示例数据
  initSampleData: function () {
    wx.showModal({
      title: '初始化示例数据',
      content: '这将添加一些示例学习记录、错题和收藏，方便你体验功能。确定继续吗？',
      success: (res) => {
        if (res.confirm) {
          InitData.initAllSampleData();
          this.loadUserStats();
          
          wx.showToast({
            title: '示例数据已添加',
            icon: 'success'
          });
        }
      }
    });
  },

  // 清空所有数据
  clearAllData: function () {
    wx.showModal({
      title: '清空所有数据',
      content: '这将清空所有学习记录、错题和收藏数据，此操作不可恢复。确定继续吗？',
      success: (res) => {
        if (res.confirm) {
          InitData.clearAllData();
          this.loadUserStats();
          
          wx.showToast({
            title: '数据已清空',
            icon: 'success'
          });
        }
      }
    });
  },

  // 跳转到学习记录
  goToStudyHistory: function () {
    wx.navigateTo({
      url: '/pages/study-history/study-history'
    });
  },

  // 跳转到错题本
  goToWrongQuestions: function () {
    wx.navigateTo({
      url: '/pages/wrong-questions/wrong-questions'
    });
  },

  // 跳转到收藏题目
  goToFavorites: function () {
    wx.navigateTo({
      url: '/pages/favorites/favorites'
    });
  },

  // 跳转到意见反馈
  goToFeedback: function () {
    wx.navigateTo({
      url: '/pages/feedback/feedback'
    });
  },

  // 跳转到关于我们
  goToAbout: function () {
    wx.navigateTo({
      url: '/pages/about/about'
    });
  },

  // 跳转到帮助中心
  goToHelp: function () {
    wx.navigateTo({
      url: '/pages/help/help'
    });
  },

  // 分享功能
  onShareAppMessage: function () {
    return {
      title: '编程题库 - 提升你的编程技能',
      path: '/pages/index/index'
    };
  },

  // 分享到朋友圈
  onShareTimeline: function () {
    return {
      title: '编程题库 - 提升你的编程技能'
    };
  }
}); 